package com.jfinal.plugin.router;

import com.jfinal.annotation.Controller;
import com.jfinal.config.Routes;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.IPlugin;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.reflections.Reflections;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.FilterBuilder;

import java.util.Set;

public class RouterPlugin implements IPlugin {

    protected Logger logger = LogManager.getLogger(getClass().getName());

    private Routes routes;

    public RouterPlugin(Routes routes){
        this.routes = routes;
    }

    public boolean start() {
        Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage("")).filterInputsBy(new FilterBuilder().include(".+\\.controller\\.[^\\.]+\\.class")));
        Set<Class<?>> controllers = reflections.getTypesAnnotatedWith(Controller.class);
        for(Class ctrl : controllers){
            Controller c = (Controller) ctrl.getAnnotation(Controller.class);
            if(StrKit.isBlank(c.viewPath())){
                routes.add(c.uri(), ctrl);
                logger.debug("[RouterPlugin] - 正在设置路由 {} -> URI:{}",ctrl,c.uri());
            }else{
                routes.add(c.uri(), ctrl,c.viewPath());
                logger.debug("[RouterPlugin] - 正在设置路由 {} -> URI:{} ; VIEW:{}",ctrl,c.uri(),c.viewPath());
            }
        }
        return true;
    }

    public boolean stop() {
        return false;
    }
}
